// import moment from 'moment';
import format from './DateHelper';

const initWebSocket = (url) => {
    try {
        const socket = new WebSocket(url);
        socket.onopen = function (msg) {
            console.log(`${url} 连接成功`);
        };
        socket.onmessage = function (msg) {
            if (typeof msg.data === "string") {
                console.log(`收到服务器消息:${msg.data}`);
            } else {
                console.log(`消息类型有误`);
            }
        };
        socket.onclose = function (msg) {
            console.log(`${url} 连接关闭`);
        };
        return socket;
    } catch (error) {
        console.log(error);
    }
    return null;
}

export default class WebUtils {

    constructor(url) {
        const self = this;
        self.WebUtilsSocket = initWebSocket(url);
    }

    /**
     * 网页通知
     *
     * @param {string} title 标题
     * @param {string} body 内容
     * @param {string} icon 图标链接
     * @param {string} sound 提示音链接
     * @memberof WebUtils
     */
    notify(title, body, icon, sound) {
        Notification.requestPermission(function (result) {
            if (result == 'granted') {
                const notification = new Notification(title, {
                    body: body,
                    icon: icon,
                    silent: true,
                });
                if (sound) {
                    //用h5播放
                    const okexAudio = new Audio(sound);
                    okexAudio.play();
                }
                notification.onclick = function () {
                    notification.close();
                };
            } else {
                alert('通知提醒已禁止,如需启用，请在浏览器选项里启用')
            }
        });
    }

    /**
     * 元素监听
     *
     * @param {object} ele document.querySelector('')
     * @param {func} callback 回调
     * @param {boolean} [observeConfig={attributes: true,childList: true}] 监听配置
     * @returns
     * @memberof WebUtils
     */
    observe(ele, callback, observeConfig = {
        attributes: true,
        childList: true
    }) {
        const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver; //浏览器兼容
        const observer = new MutationObserver(function (mutations) { //构造函数回调
            mutations.forEach(function (record) {
                callback(record);
            });
        });
        observer.observe(ele, observeConfig);
        return observer;
    }

    /**
     * WebSocket发送消息
     *
     * @param {string} msg 消息
     * @memberof WebUtils
     */
    webSocketSend(msg) {
        const self = this;
        if (!!self.WebUtilsSocket) {
            self.WebUtilsSocket.send(msg);
        }
    }

    /**
     * 日志
     *
     * @param {string} msg 日志信息
     * @param {number} [logLever=2] 0<1<2<3<4<5 => ALL < DEBUG < INFO < WARN < ERROR < FATAL
     * @memberof WebUtils
     */
    log(msg, logLever = 2) {
        const self = this;
        if (typeof msg === 'object') {
            msg = JSON.stringify(msg);
        }
        // console.log(`${moment().format('YYYY-MM-DD HH:mm:ss.S')}:${msg}`);
        console.log(`${format(new Date(), "yyyy-MM-dd hh:mm:ss.S")}:${msg}`);
        if (logLever > 1 && !!self.WebUtilsSocket && self.WebUtilsSocket.readyState === 1) {
            self.webSocketSend(`jslog:${msg}`);
        }
    }

    /**
     * 异步请求
     *
     * @param {function} func 需异步请求的函数，剩余参数传函数所需参数 
     * @returns
     * @memberof WebUtils
     */
    taskRun(func) {
        return new Promise((resolve, reject) => {
            if (typeof func !== 'function') {
                reject(`函数有误`);
                return;
            }
            setTimeout(() => {
                try {
                    const thatArgs = [...arguments];
                    const funcArgs = thatArgs.splice(1);
                    resolve(func(...funcArgs));
                } catch (error) {
                    reject(error);
                }
            }, 0);
        });
    }
}